package com.fs.service.impl;


import com.fs.dao.DiscusstionDao;
import com.fs.dao.UserDao;
import com.fs.pojo.Discusstion;
import com.fs.pojo.User;
import com.fs.service.DiscusstionService;
import com.fs.utils.BeanFactories;
import com.fs.utils.IdWorker;
import com.fs.utils.JDBCUtils;
import com.fs.vo.DiscusstionVO;
import net.sf.cglib.beans.BeanCopier;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (TbDiscusstion)表服务实现类
 *
 * @author makejava
 * @since 2022-11-15 10:21:17
 */

public class DiscusstionServiceImpl implements DiscusstionService {

    private DiscusstionDao discusstionDao = BeanFactories.getBean(DiscusstionDao.class);
    private UserDao userDao = BeanFactories.getBean(UserDao.class);


    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /**
     * 根据classId获取所有讨论主题
     * @param classId
     * @return
     */
    @Override
    public List<DiscusstionVO> getAllDiscusstionByClassId(String classId) {

        //查询出所有在classId班级下的讨论内容
        List<Discusstion> discusstions = discusstionDao.queryAllByClassId(classId);

        //通过stream流转为VO集合
        List<DiscusstionVO> vos = discusstions.stream().map(discusstion -> {

            DiscusstionVO vo = new DiscusstionVO();

            //先拷贝不同类的属性
            User user = userDao.queryById(discusstion.getUserId());
            BeanCopier.create(User.class,DiscusstionVO.class,false).copy(user,vo,null);

            //再拷贝同类属性
            BeanCopier.create(Discusstion.class, DiscusstionVO.class, false).copy(discusstion, vo, null);




            return vo;

        }).collect(Collectors.toList());

        //根据回复者身份，回复量，时间排序排序
        vos.sort((vo1,vo2) ->{

            int s1 = vo1.getRole().compareTo(vo2.getRole());
            int s2 = vo1.getReplies().compareTo(vo2.getReplies());
            int s3 = vo1.getPulishTime().compareTo(vo2.getPulishTime());

            return  -(s1+s2+s3);
        });

        return vos;
    }

    /**
     * 发布主题
     * @param discusstion
     * @return
     */
    @Override
    public boolean pulishDiscusstion(Discusstion discusstion){


        discusstion.setPulishTime(sdf.format(new Date()));

        discusstion.setViews(0);
        discusstion.setReplies(0);

        //雪花算法生成id
        discusstion.setId( new IdWorker().nextId()+"");

        return  discusstionDao.insert(discusstion) > 0;

    }


    @Override
    public Discusstion queryById(String id) {


        return discusstionDao.queryById(id);
    }

    @Override
    public List<Discusstion> queryAll() {
        return null;
    }

    @Override
    public int insert(Discusstion obj) {
        return 0;
    }

    @Override
    public int deleteById(String id) {
        return 0;
    }

    @Override
    public int update(Discusstion obj) {
        return 0;
    }
}
